<!doctype html>
<html>

	<head>
		<meta charset="UTF-8">
		<title></title>
		<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
		<link href="../../css/mui.min.css" rel="stylesheet" />
		<style>
			.ignore_btn{
				width: 60px;
				height: 35px;
			}
			.pass_btn{
				width: 60px;
				height: 35px;
			}
		</style>
	</head>

	<body>
		
		<div class="mui-content">
		    <ul class="mui-table-view" id="ul_friend_request_list" style="margin-bottom: 10px;">
		    </ul>
		    
		    <ul class="mui-table-view" id="ul_chatSnapshot">
		        <!--<li class="mui-table-view-cell mui-media">
	                <div class="mui-media-body">
	                	<img class="mui-media-object mui-pull-left" src="../../img/bg.jpg" style="width: 40px;height: 40px;line-height: 40px;border-radius: 5px;"/>
	                    	鲁海
	                    <p class="mui-ellipsis">最新的聊天内容</p>
	                </div> 
		        </li>-->
		    </ul>
		</div>
		
		<script src="../../js/mui.min.js"></script>
		<script type="text/javascript" src="../../js/app.js" ></script>
		<script type="text/javascript">
			mui.init()
			
			mui.plusReady(function(){
				
				var userInfo = app.getUserInfo();
				
				//加载当前的tab时触发
				var currentView = plus.webview.currentWebview();
				console.log(JSON.stringify(currentView));
				currentView.addEventListener("show", function() {
					showFriendRequestList();
					
					fetchUnReadMsg();
				});
				
				//自定义刷新列表
				window.addEventListener("refreshPage", function(event){
					console.log("执行了chatList");
					showFriendRequestList();
					console.log("websocket初始化");
					CHAT.init();
				});
				
				//跳转聊天页面
				mui("#ul_chatSnapshot").on('tap',".chat_with_friend", function() {
					
					var friendId = this.getAttribute("friendId");
					var friendMarkName = this.getAttribute("markName");
					var friendAvatar = this.getAttribute("avatar");
					
					mui.openWindow({
						url:'../chat/feixin_chat.html', 
						id:"chatting-" + friendId,
						extras:{
							friendId: friendId,
							friendMarkName: friendMarkName,
							friendAvatar: friendAvatar
						}
					});
					
					//标记未读消息为已读
					app.readFriendChatSnapshot(userInfo.userId, friendId);
					// 渲染快照列表进行展示
					loadingChatSnapshot();
				});
				
				//删除聊天记录
				mui("#ul_chatSnapshot").on("tap", "#link_delChatRecord", function(){
					var me = this;
					var friendId = me.getAttribute("id");
					
					//删除聊天记录
					app.removeFriendChatHistory(userInfo.userId, friendId);
					//删除聊天快照
					app.removeFriendChatSnapshot(userInfo.userId, friendId);
					//移除li
					var li = me.parentNode.parentNode; //获取li
					var ul_chatSnapshot = document.getElementById("ul_chatSnapshot");
					ul_chatSnapshot.removeChild(li);
				});
				
			});
			
			window.CHAT = {
				socket: null,
				init: function() {
					if (window.WebSocket) {
						
						// 如果当前的状态已经连接，那就不需要重复初始化websocket
						if (CHAT.socket != null 
							&& CHAT.socket != undefined 
							&& CHAT.socket.readyState == WebSocket.OPEN) {
							return false;
						}
						
						CHAT.socket = new WebSocket(app.nettyServerUrl);
						CHAT.socket.onopen = CHAT.wsopen,
						CHAT.socket.onclose = CHAT.wsclose,
						CHAT.socket.onerror = CHAT.wserror,
						CHAT.socket.onmessage = CHAT.wsmessage;
					} else {
						alert("手机设备过旧，请升级手机设备...");
					}
				},
				chat: function(msg) {
					
					console.log("当前的信息：" + msg);
					
					// 如果当前websocket的状态是已打开，则直接发送， 否则重连
					if (CHAT.socket != null 
							&& CHAT.socket != undefined  
							&& CHAT.socket.readyState == WebSocket.OPEN) {
							CHAT.socket.send(msg);
					} else {
						// 重连websocket
						CHAT.init();
						setTimeout("CHAT.reChat('" + msg + "')", "1000");
					}
					// 渲染快照列表进行展示
					loadingChatSnapshot();
				},
				reChat: function(msg) {
					console.log("消息重新发送...");
					CHAT.socket.send(msg);
				},
				wsopen: function() {
					console.log("websocket连接已建立...");
					
					var me = app.getUserInfo();
					// 构建ChatMsg
					var chatMsg = new app.ChatMsg(me.userId, null, null, null);
					// 构建MessageData
					var dataContent = new app.MessageData(app.MSG_CONNECT, chatMsg, null);
					// 发送websocket
					CHAT.chat(JSON.stringify(dataContent));
					
					// 每次连接之后，获取用户的未读未签收消息列表
					fetchUnReadMsg();
					
					// 定时发送心跳
					setInterval("CHAT.keepalive()", 30000);
				},
				wsmessage: function(e) {
					console.log("接受到消息：" + e.data);
					
					// 转换MessageData为对象
					var dataContent = JSON.parse(e.data);
					var action = dataContent.action;
					if (action === app.MSG_PULL_FRIEND) {
						getFriendList();
						return false;						
					}
					
					// 如果不是重新拉取好友列表，则获取聊天消息模型，渲染接收到的聊天记录
					var chatMsg = dataContent.chatMsg;
					var msg = chatMsg.msg;
					var friendUserId = chatMsg.senderId;
					var myId = chatMsg.receiverId;
					
					// 调用聊天webview的receiveMsg方法
					var chatWebview = plus.webview.getWebviewById("chatting-" + friendUserId);
					var isRead = true;
					if (chatWebview != null) {
						chatWebview.evalJS("receiveMsg('" + msg + "')");
						chatWebview.evalJS("resizeScroll()");
					} else {
						isRead = false;	// chatWebview 聊天页面没有打开，标记消息未读状态
					}
					
					// 接受到消息之后，对消息记录进行签收
					var dataContentSign = new app.MessageData(app.MSG_SIGNED, null, chatMsg.msgId);
					CHAT.chat(JSON.stringify(dataContentSign));
					
					// 保存聊天历史记录到本地缓存
					app.saveFriendChatHistory(myId, friendUserId, msg, app.FRIEND_MSG);
					app.saveFriendChatSnapshot(myId, friendUserId, msg, isRead);
					// 渲染快照列表进行展示
					loadingChatSnapshot();
				},
				wsclose: function() {
					console.log("连接关闭...");
				},
				wserror: function() {
					console.log("发生错误...");
				},
				signMsgList: function(unSignedMsgIds) {
					// 构建批量签收对象的模型
					var dataContentSign = new app.MessageData(app.MSG_SIGNED, null, unSignedMsgIds);
					// 发送批量签收的请求
					CHAT.chat(JSON.stringify(dataContentSign));
				},
				keepalive: function() {
					// 构建对象
					var dataContent = new app.MessageData(app.MSG_KEEP_ALIVE, null, null);
					// 发送心跳
					CHAT.chat(JSON.stringify(dataContent));
					
					// 定时执行函数
					fetchUnReadMsg();
					getFriendList();
				}
			}
			
			//每次重连后获取服务器的未签收消息
			function fetchUnReadMsg() {
				var user = app.getUserInfo();
				var msgIds = ",";	// 格式：  ,1001,1002,1003,
				mui.ajax(app.serverUrl + "/simple-chat/api/friends/unread",{
					data:{
						receiverId: user.userId
					},
					dataType:'json',
					type:'post',
					timeout:10000,
					headers:{'Authorization':'Bearer ' + app.getToken()},		              
					success:function(data){
						
						if (data.status == 0) {
							var unReadMsgList = data.data;
							console.log("未读消息：" + JSON.stringify(unReadMsgList));
							
							// 1. 保存聊天记录到本地
							// 2. 保存聊天快照到本地
							// 3. 对这些未签收的消息，批量签收
							for (var i = 0 ; i < unReadMsgList.length ; i ++) {
								var msgObj = unReadMsgList[i];
								// 逐条存入聊天记录
								app.saveFriendChatHistory(msgObj.receiverId, msgObj.senderId, msgObj.msg, app.FRIEND_MSG);
								// 存入聊天快照
								app.saveFriendChatSnapshot(msgObj.receiverId, msgObj.senderId, msgObj.msg, false);
								// 拼接批量接受的消息id字符串，逗号间隔
								msgIds += msgObj.msgId;
								msgIds += ",";
							}
							
							// 批量签收
							CHAT.signMsgList(msgIds);
							// 刷新快照
							loadingChatSnapshot();
						}
					}
				});
			}
			
			// 展示聊天快照，渲染列表
			function loadingChatSnapshot() {
				var user = app.getUserInfo();
				console.log("传进来userId:" + user.userId);
				var chatSnapshotList = app.getFriendChatSnapshot(user.userId);
				
				var chatItemHtml = "";
				var ul_chatSnapshot = document.getElementById("ul_chatSnapshot");
				ul_chatSnapshot.innerHTML = "";
				for (var i = 0 ; i < chatSnapshotList.length ; i ++) {
					var chatItem = chatSnapshotList[i];
					
					var friendId = chatItem.friendId;
					
					console.log("朋友ID：" + friendId);
					
					// 根据friendId从本地联系人列表的缓存中拿到相关信息
					var friend = app.getFriendFromFriendList(friendId);
					
					// 判断消息的已读或未读状态
					var isRead = chatItem.isRead;
					var readHtmlBefore = '';
					var readHtmlAfter = '';
					if (!isRead) {
						readHtmlBefore = '<span class="red-point">';
						readHtmlAfter = '</span>';
					}
					
					chatItemHtml = "";
					
					if(friend != null) {
						
						console.log("朋友：" + JSON.stringify(friend));
						
						chatItemHtml =  '<li friendId="'+ friendId +'" markName="'+ friend.markName +'" avatar="'+ friend.avatar +'"  class="chat_with_friend mui-table-view-cell mui-media">' +
											'<div class="mui-slider-right mui-disabled">' +
												'<a id="link_delChatRecord" id="' + friendId + '" class="mui-btn mui-btn-red">删除</a>' +
											'</div>' +
											'<div class="mui-slider-handle mui-media-body ">' +
									            '<img class="mui-media-object mui-pull-left" src="' + friend.avatar+ '"/>' +
									            	readHtmlBefore + friend.markName  + readHtmlAfter + 
									            '<p class="mui-ellipsis">' + chatItem.msg + '</p>' +
								            '</div>' +
									    '</li>';
					}
					
					ul_chatSnapshot.insertAdjacentHTML('beforeend', chatItemHtml);
				}
				
			}

			function getFriendList() {
				
				var userInfo = app.getUserInfo();
				
				mui.ajax(app.serverUrl + '/simple-chat/api/friends/' + userInfo.userId,{
					dataType:'json',
					type:'get',
					timeout:10000,
					headers:{'Authorization':'Bearer ' + app.getToken()},	              
					success:function(data){
						var friendList = data.data;
						app.setFriendList(friendList);
					}
				});
			}
			
			function showFriendRequestList() {
				var userInfo = app.getUserInfo();
				
				mui.ajax(app.serverUrl + "/simple-chat/api/friends/request/" + userInfo.userId,{
					dataType:'json',
					type:'get',
					timeout:10000,
					headers:{'Authorization':'Bearer ' + app.getToken()},  	              
					success:function(data){
						
						console.log("获取添加好友请求结果：" + JSON.stringify(data.data));
						var friendRequestList = data.data;
						var friend_request_list = document.getElementById("ul_friend_request_list");
						if(friendRequestList != null && friendRequestList.length > 0) {
							var friendRequestListHtml = "";
							for(var i = 0; i < friendRequestList.length; i++) {
								friendRequestListHtml += getFriendRequestListHtml(friendRequestList[i]);
							}
							
							//追加html到ul
							friend_request_list.innerHTML = friendRequestListHtml;
							
							//动态绑定忽略和同意按钮点击事件
							mui(".btnOper").on("tap", ".ignore_btn", function(e){
								var friendId = this.getAttribute("friendId");
								operateFriendRequest(friendId, userInfo.userId, 0);
							});
							
							mui(".btnOper").on("tap", ".pass_btn", function(e){
								var friendId = this.getAttribute("friendId");
								operateFriendRequest(friendId, userInfo.userId, 1);
							});
						}else{
							friend_request_list.innerHTML = "";
						}
					}
				});
			}
			
			function getFriendRequestListHtml(friend) {		
				var html = "";
				html = '<li class="btnOper mui-table-view-cell mui-media">' +
		            		'<a href="javascript:;">' +
		                		'<img class="mui-media-object mui-pull-left" src="'+ friend.avatar +'" style="width: 50px;border-radius: 5px;">' +
				                '<span id="span_nickname" class="mui-pull-right">' +
				                	'<button friendId="'+ friend.userId +'" type="button" class="ignore_btn mui-btn mui-btn-grey" style="padding: 4px 10px;margin-right: 5px;">忽略</button>' +
				                	'<button friendId="'+ friend.userId +'" type="button" class="pass_btn mui-btn mui-btn-danger" style="padding: 4px 10px;">同意</button>' +
				                '</span>' +
				                '<div class="mui-media-body">' +
				                    '<label>'+ friend.nickname +'</label>' +
				                    '<p class="mui-ellipsis">请求添加您为好友</p>' +
				                '</div>' +
				            '</a>' +
				        '</li>';
				return html;
			}
			
			//type 0:拒绝  1:同意
			function operateFriendRequest(senderId, receiveId, type) {
				var operateUrl = app.serverUrl;
				if(type == 0) {
					operateUrl += "/simple-chat/api/friends/refuse";
				}else {
					operateUrl += "/simple-chat/api/friends/agree";
				}
				
				mui.ajax(operateUrl, {
					data:{
						sendId: senderId,
						receiveId: receiveId
					},
					dataType:'json',
					type:'post',
					timeout:10000,
					headers:{'Authorization':'Bearer ' + app.getToken()}, 	              
					success:function(data){
						//重新加载
						showFriendRequestList();
					},
					error:function(xhr,type,errorThrown){
						app.showToast("网络异常，请检查您的网络", "error");
					}
				});
			}
		</script>
	</body>

</html>